
import { globalUtils } from '../../common/js/global-utils/global-utils-all';
import { uiUtils } from '../../common/js/ui-utils/ui-utils-all';
import Pure from 'pure-frontend';
import uiData from 'ui-data';
import { CurrentRunningApp } from '../../common/js/current-running-app';

/* SOURCE-CODE-START */

"use strict";


Pure.app.viewMain('profile-management', function (scope, view) {
  var dataModel = view.getDataModel();
  var jqTable = view.$ui('profileTable');
  var jqSearchBtn = view.$ui('searchBtn');
  var jqCreateBtn = view.$ui('createBtn');
  var jqNewProfileDialog = view.$ui('newProfileDialog');
  var jqNewProfileForm = jqNewProfileDialog.find('form');
  var jqEditProfileDialog = view.$ui('editProfileDialog');
  var jqEditProfileForm = jqEditProfileDialog.find('form');
  var currentTenantId = CurrentRunningApp.data[CurrentRunningApp.DATA_TENANT_ID];
  var systemTenantFlag = (currentTenantId === globalConfig.SYSTEM_TENANT_ID);

  if (systemTenantFlag) {
    jqCreateBtn.removeAttr('hidden');
  }

  // 初始表格
  uiUtils.dataGrid.init(jqTable, {
    url: 'api/infrastructure/profile/pageProfileItemsByCond',
    columns: [
      {
        field: 'id'
      },
      {
        field: 'itemCode'
      },
      {
        field: 'itemName'
      },
      {
        field: 'itemDesc'
      },
      {
        field: 'enableFlagDesc'
      },
      {
        field: 'operate',
        'class': 'x-nowrap-items',
        formatter: formatOprationColumn,
        events: {
          'click .edit': clickEditOperationFn,
          'click .delete': clickEditOperationFn,
          'click .detail': clickDetailOperationFn,
          'click .optionList': clickOptionListOperationFn
        }
      }
    ]
  });

  function formatOprationColumn(value, row, index) {
    if (systemTenantFlag) {
      return [
        '<a class="edit" href="javascript:void(0)">',
        '<span>${t("ui.system.common.operation.edit")}</span>',
        '</a>',
        '&nbsp;',
        '<a class="detail" href="javascript:void(0)">',
        '<span>${t("ui.system.common.operation.detail")}</span>',
        '</a>'
      ].join('');
    } else {
      return [
        '<a class="detail" href="javascript:void(0)">',
        '<span>${t("ui.system.common.operation.detail")}</span>',
        '</a>'
      ].join('');
    }
  }

  jqSearchBtn.on(uiUtils.event.CLICK, function () {
    var data = dataModel.getData('searchField.*');
    data = uiData.utils.unprefix(data, 'searchField.');

    uiUtils.dataGrid.newQuery(jqTable, {
      customQuery: data
    });
  });


  // 点击创建按钮的事件
  jqCreateBtn.on(uiUtils.event.CLICK, function () {
    // 显示弹出框
    uiUtils.dialog.showModal(jqNewProfileDialog, {
      backdropParent: view.getViewElement(),
      onModalHide: function () {
        uiUtils.common.resetValidation(jqNewProfileForm);
      }
    });

    // 离开页面时检查是否表单发生变更
    uiUtils.view.setCurrentFormDataToContext(scope, getNewData);
    uiUtils.view.checkFormDataChangeWhenLeave(scope, getNewData);
  });

  var profileValidationRule = {
    rules: {
      itemCode: {
        required: true,
        maxlength: 50,
        customCode: true
      },
      itemName: {
        required: true,
        maxlength: 100
      },
      itemDesc: {
        maxlength: 200
      }
    },
    messages: {
      itemCode: {
        required: '${t("ui.infrastructure.profile.validation.itemCodeRequired")}'
      },
      itemName: {
        required: '${t("ui.infrastructure.profile.validation.itemNameRequired")}'
      }
    }
  };

  //
  // "新建系统参数"弹出框
  //

  // 定义新建记录的校验规则
  jqNewProfileForm.validate(profileValidationRule);

  // 点击"新建系统参数"弹出框的保存按钮
  jqNewProfileDialog.on(uiUtils.event.CLICK, uiUtils.dialog.BTN_CONFIRM, function () {
    var checkResult = jqNewProfileForm.valid();
    if (!checkResult) {
      return;
    }

    var data = dataModel.getData('new.*');
    data = uiData.utils.unprefix(data, 'new.');

    // 调用保存记录的接口
    view.callService('api/infrastructure/profile/saveProfileItem', data)
      .waitResult(function (saveResult) {
        if (!uiUtils.common.checkWebResultSuccess(saveResult)) {
          return;
        }

        uiUtils.dialog.hideModal(jqNewProfileDialog);
        Pure.app.showMessage('${t("ui.system.common.msg.saveRecordSuccess")}');
        uiUtils.dataGrid.refresh(jqTable);
      });
  });

  jqNewProfileDialog.on(uiUtils.event.MODAL_HIDE, function () {
    uiUtils.view.notCheckFormDataChangeWhenLeave(scope);
  });

  function getNewData() {
    return dataModel.getData('new.*');
  }

  //
  // "编辑系统参数"弹出框
  //

  jqEditProfileForm.validate(profileValidationRule);

  // 点击"编辑系统参数"弹出框的保存按钮
  jqEditProfileDialog.on(uiUtils.event.CLICK, uiUtils.dialog.BTN_CONFIRM, function () {
    var checkResult = jqEditProfileForm.valid();
    if (!checkResult) {
      return;
    }

    var data = dataModel.getData('edit.*');
    data = uiData.utils.unprefix(data, 'edit.', true);

    // 调用更新记录的接口
    view.callService('api/infrastructure/profile/updateProfileItem', data)
      .waitResult(function (result) {
        if (result.success) {
          uiUtils.dialog.hideModal(jqEditProfileDialog);
          Pure.app.showMessage('${t("ui.system.common.msg.saveRecordSuccess")}');
          uiUtils.dataGrid.refresh(jqTable);
        } else {
          Pure.app.showError(result.message);
        }
      });
  });

  jqEditProfileDialog.on(uiUtils.event.MODAL_HIDE, function () {
    uiUtils.view.notCheckFormDataChangeWhenLeave(scope);
  });

  function getEditData() {
    return dataModel.getData('edit.*');
  }

  //
  //
  //

  /**
   * 点击"编辑"操作的事件
   * @param {*} e 
   * @param {*} value 
   * @param {*} row 
   * @param {*} index 
   */
  function clickEditOperationFn(e, value, row, index) {
    uiUtils.dialog.showModal(jqEditProfileDialog, {
      backdropParent: view.getViewElement(),
      onModalHide: function () {
        uiUtils.common.resetValidation(jqEditProfileForm);
      }
    });

    var queryParams = {
      id: row.id
    };

    // 调用接口获取记录
    view.callService('api/infrastructure/profile/getProfileItemById', queryParams)
      .waitResult(function (result, textStatus, jqXHR) {
        if (!uiUtils.common.checkWebResultSuccess(result)) {
          return;
        }

        var data = uiData.utils.prefix(result.data, 'edit.');
        dataModel.setData('edit.*', data);

        // 离开页面时检查是否表单发生变更
        uiUtils.view.setCurrentFormDataToContext(scope, getEditData);
        uiUtils.view.checkFormDataChangeWhenLeave(scope, getEditData);
      });
  }

  /**
   * 点击"删除"操作的事件
   * @param {*} e 
   * @param {*} value 
   * @param {*} row 
   * @param {*} index 
   */
  function clickDeleteOperationFn(e, value, row, index) {
    // TODO
    alert('${t("ui.system.common.msg.functionIsNotImplemented")}');
  }

  /**
   * 点击"详情"操作的事件
   * @param {*} e 
   * @param {*} value 
   * @param {*} row 
   * @param {*} index 
   */
  function clickDetailOperationFn(e, value, row, index) {
    var id = row.id;
    var url = globalUtils.formatString('app/infrastructure/profile/detail/{0}', id);

    Pure.app.pushView(url);
  }

  /**
   * 点击"选项列表"操作的事件
   * @param {*} e 
   * @param {*} value 
   * @param {*} row 
   * @param {*} index 
   */
  function clickOptionListOperationFn(e, value, row, index) {
    // TODO
    alert('${t("ui.system.common.msg.functionIsNotImplemented")}');
  }

});

/* SOURCE-CODE-END */
